﻿                                                         using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.PalletInfos;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.DeviceMsgs;
using HamcoWcs.Models.Devices;
using HamcoWcs.Models.MainTasks;
using HamcoWcs.Workers;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System.Linq;

namespace HamcoWcs.Service.Pcon.PconPlcDbMsgParsers
{
    public class PconMsgParse_MaterialRequest : PconMsgParseBase
    {
        private readonly ILoggerService _loggerService;
        private readonly IBaseTaskService _baseTaskService;
        public override EnumPconPlcRequest RequestType => EnumPconPlcRequest.MaterialRequest;

        public PconMsgParse_MaterialRequest(IMapper mapper, WcsDbContext wcsDbContext,
            IBaseTaskService baseTaskService, ILoggerService loggerService)
            : base(null, wcsDbContext, mapper)
        {
            _baseTaskService = baseTaskService;
            _loggerService = loggerService;
        }

        // offset 32   /   132
        public override void Deal(PconDto pconDto, PconPlc pconPlc)
        {
            
            if (!(pconDto.MachineName == "CJMCV500" || pconDto.MachineName == "CJMCV600")) return;

            var palletInfo = _wcsDbContext.Set<PalletInfo>().FirstOrDefault(x => x.UnitId == pconDto.UnitId);



            var materialStr = "ERROR";
            if (palletInfo is null)
            {
                materialStr = "ERROR";
            }
            else
            {
                MaterialInfo materialInfo = JsonConvert.DeserializeObject<MaterialInfo>(palletInfo.MaterialInfo);
                if (materialInfo is null) materialStr = "ERROR";
                materialStr = string.Join('|', materialInfo.MaterialList);
            }

         

          

            MaterialSendInfo a = new MaterialSendInfo()
            {
                MaterialLength = 100,
                MaterialSendPoint = pconDto.MachineName == "CJMCV600" ? 32 : 132,
                Msg = new PconSendMsg()
                {
                    Request = (ushort)EnumPconSendMsg.MaterialInfoSendCmd
                },
                MaterialStr = materialStr,
                SendStartPoint = pconDto.SendStartPoint
                
            };

            PconWorker.MATERIAL_SEND_BUFFERS.Enqueue(a);
        }
    }
}
